package com.yc.vote.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yc.vote.entity.Items;
import com.yc.vote.entity.Vote;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 投票系统-题目表-2 Mapper 接口
 * </p>
 *
 * @author baomidou
 * @since 2024-04-14
 */
public interface VoteMapper extends BaseMapper<Vote> {

    @Select("select * from tp_vote where id=#{id}")
    @Results(
            id = "rm1",
            // 手工的字段映射 + 关联查询
            value = {
                    // 映射主键字段
                    // id 映射有特殊含义, 与缓存有关, 提升性能
                    @Result(column = "id", property = "id", id = true),
                    @Result(column = "id", property = "items",
                            many = @Many(select = "selectItemsByVid")),
                    @Result(column = "id", property = "unum",
                            one = @One(select = "countUnumByVid"))
            }
    )
    Vote selectById(int id);

    @Select("select a.*, IFNULL(b.cnt,0) unum\n" +
            " from tp_items a\n" +
            " left join (select iid, count(*) cnt\n" +
            "              from tp_record\n" +
            "             where vid=#{vid}\n" +
            "             group by iid) b on a.id=b.iid\n" +
            " where vid=#{vid}")
    List<Items> selectItemsByVid(int vid);

    @Select("select count(DISTINCT usid) unum,vid\n" +
            "  from tp_record\n" +
            " where vid = #{vid}\n" +
            " group by vid")
    int countUnumByVid(int vid);

    @Select("<script>" +
            "select * from tp_vote" +
            "<where>" +
            " status = 1 " +  // 查询, 排除逻辑删除的记录
            "<if test='vname!=null'>and vname like concat('%',#{vname},'%')</if>" +
            "</where>" +
            "</script>")
    @ResultMap("rm1")
    List<Vote> selectLikeVname(@Param("vname") String vname);


    //MyBatisPlus 分页查询
    @Select("<script>" +
            "select * from tp_vote" +
            "<where>" +
            " status = 1 " +  // 查询, 排除逻辑删除的记录
            "<if test='vname!=null'>and vname like concat('%',#{vname},'%')</if>" +
            "</where>" +
            "</script>")
    @ResultMap("rm1")
    IPage<Vote> selectLikeVname(@Param("vname") String vname, IPage<Vote> page);

}
